//
//  YHCheckBoxView.m
//  ScriptKill
//
//  Created by 林宁宁 on 2021/4/9.
//  Copyright © 2021 优智汇. All rights reserved.
//

#import "YHCheckBoxView.h"
#import "UIButton+YH.h"
#import "YHBaseCollectionViewCell.h"
#import "NSString+YH.h"
#import "UIFont+YH.h"
#import "UIColor+YHStyle.h"
#import "NSObject+YHKVO.h"
#import "YHDefines.h"
#import "UIView+YHFrame.h"
#import "YHHUD.h"

@interface YHCheckBoxViewCell : YHBaseCollectionViewCell

@property (retain, nonatomic) UIButton * checkView;
@property (retain, nonatomic) UILabel * titleView;

@end

@implementation YHCheckBoxViewCell

+ (NSString *)cellIndentifyVertical{
    return [self cellIndentify].yh_append(@"Vertical");
}

- (void)yh_commonInit{
    self.checkView = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.checkView setImage:[UIImage imageNamed:@"circle.dashed"] forState:UIControlStateNormal];
    [self.checkView setImage:[UIImage imageNamed:@"circle.dashed.inset.filled"] forState:UIControlStateSelected];
    self.checkView.userInteractionEnabled = NO;
    [self.contentView addSubview:self.checkView];
    
    self.titleView = [UILabel new];
    self.titleView.font = [UIFont yh_pfOfSize:14];
    self.titleView.textColor = [UIColor yh_h1];
    self.titleView.textAlignment = NSTextAlignmentLeft;
    [self.contentView addSubview:self.titleView];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    if([self.reuseIdentifier isEqualToString:[self.class cellIndentifyVertical]]){
        [self.checkView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contentView).offset(15);
            make.centerY.equalTo(self.contentView);
        }];
        
        [self.titleView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contentView).offset(10 + 15 + 20);
            make.centerY.equalTo(self.contentView);
        }];
    }else{
        [self.checkView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contentView);
            make.centerY.equalTo(self.contentView);
        }];
        
        [self.titleView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.checkView.mas_right).offset(5);
            make.centerY.equalTo(self.contentView);
            make.right.equalTo(self.contentView);
        }];
    }
}

@end


@interface YHCheckBoxView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (retain, nonatomic) UICollectionView * collectionView;

@property (retain, nonatomic) NSMutableArray <YHCheckBoxItem *>* dataList;

@property (retain, nonatomic) NSMutableArray <YHCheckBoxItem *>* selectList;

@end

@implementation YHCheckBoxView

-(void)yh_commonInit{
    
    self.config = [YHCheckBoxLayoutConfig new];
    
    UICollectionViewFlowLayout * flowlayout = [UICollectionViewFlowLayout new];
    flowlayout.scrollDirection = self.config.scrollDirection;
    flowlayout.minimumLineSpacing = self.config.space;
    flowlayout.minimumInteritemSpacing = self.config.space;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowlayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    [self.collectionView registerClass:YHCheckBoxViewCell.class forCellWithReuseIdentifier:YHCheckBoxViewCell.cellIndentify];
    [self.collectionView registerClass:YHCheckBoxViewCell.class forCellWithReuseIdentifier:YHCheckBoxViewCell.cellIndentifyVertical];
    
    
    self.dataList = [NSMutableArray new];
    self.selectList = [NSMutableArray new];
    
    WS(weakSelf)
    [self yh_kvoForKeyPath:@"contentSize" observe:self.collectionView block:^(id  _Nonnull obj, id  _Nullable oldVal, id  _Nullable newVal) {
        [weakSelf relayoutContentView];
    }];
    
    [self yh_kvoForKeyPath:@"scrollDirection" observe:self.config block:^(id  _Nonnull obj, id  _Nullable oldVal, id  _Nullable newVal) {
        UICollectionViewFlowLayout * flowlayout = [UICollectionViewFlowLayout new];
        flowlayout.scrollDirection = weakSelf.config.scrollDirection;
        flowlayout.minimumLineSpacing = weakSelf.config.space;
        flowlayout.minimumInteritemSpacing = weakSelf.config.space;
        weakSelf.collectionView.collectionViewLayout = flowlayout;
        [weakSelf.collectionView reloadData];
    }];
}

-(void)layoutSubviews{
    [super layoutSubviews];
    
    [self relayoutContentView];
}

- (void)relayoutContentView{
    
    if(CGRectIsEmpty(self.collectionView.frame)){
        return;
    }
    
    if(self.config.scrollDirection == UICollectionViewScrollDirectionVertical){
        return;
    }
    if(self.config.isLayoutCenter){
        CGFloat contentWidth = self.collectionView.contentSize.width;
        if(contentWidth == 0){
            return;
        }
        CGFloat originX = 0;
        if(contentWidth < self.yh_width){
            //设置居中布局
            originX = (self.yh_width - contentWidth)*0.5;
        }else{
            //超过父视图 宽度 转左边开始布局
            originX = 0;
        }
        self.collectionView.contentInset = UIEdgeInsetsMake(0, originX, 0, 0);
    }
    
}

- (NSArray <YHCheckBoxItem *>*)currentSelectItems{
    return self.selectList;
}

- (void)addCheckTitles:(NSArray <NSString *>*)titles{
    for(NSString * title in titles){
        [self addCheckItemTitle:title ID:title];
    }
}

- (void)cleanAllCheckItems{
    [self.dataList removeAllObjects];
    [self.selectList removeAllObjects];
    [self.collectionView reloadData];
}

- (void)addCheckItemTitle:(NSString *)title
                       ID:(NSString * _Nullable)ID{
    [self addCheckItemTitle:title ID:ID type:0 isSelect:NO];
}
- (void)addCheckItemTitle:(NSString *)title
                     type:(NSInteger)type{
    [self addCheckItemTitle:title ID:nil type:type isSelect:NO];
}

- (void)addCheckItemTitle:(NSString *)title
                       ID:(NSString * _Nullable)ID
                     type:(NSInteger)type
                 isSelect:(BOOL)isSelect{
    YHCheckBoxItem * item = [YHCheckBoxItem new];
    item.title = title;
    item.ID = ID;
    item.type = type;
    [self.dataList addObject:item];
    if(isSelect){
        [self.selectList addObject:item];
    }
    [self.collectionView reloadData];
}

/// 选中该标题
- (void)selectCheckTitle:(NSString *)title{
    for(YHCheckBoxItem * item in self.dataList){
        if([item.title isEqualToString:title] &&
           ![self.selectList containsObject:item]){
            [self.selectList addObject:item];
            [self.collectionView reloadData];
            return;
        }
    }
}
/// 选中该类型
- (void)selectCheckType:(NSInteger)type{
    for(YHCheckBoxItem * item in self.dataList){
        if(item.type == type &&
           ![self.selectList containsObject:item]){
            [self.selectList addObject:item];
            [self.collectionView reloadData];
            return;
        }
    }
}
 

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataList.count;
}

-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YHCheckBoxViewCell * cell;
    if(self.config.scrollDirection == UICollectionViewScrollDirectionVertical){
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:YHCheckBoxViewCell.cellIndentifyVertical forIndexPath:indexPath];
    }else{
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:YHCheckBoxViewCell.cellIndentify forIndexPath:indexPath];
    }
        
    YHCheckBoxItem * item = self.dataList[indexPath.row];
    cell.titleView.text = item.title;
    
    [cell.checkView setImage:[UIImage imageNamed:self.config.imageNormal] forState:UIControlStateNormal];
    [cell.checkView setImage:[UIImage imageNamed:self.config.imageSelect] forState:UIControlStateSelected];
    if([self.selectList containsObject:item]){
        cell.checkView.selected = YES;
    }else{
        cell.checkView.selected = NO;
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    YHCheckBoxItem * item = self.dataList[indexPath.row];
    if(self.checkType == YHCheckBoxSelectSingle){
        [self.selectList removeAllObjects];
        [self.selectList addObject:item];
    }
    else if(self.checkType == YHCheckBoxSelectMultiple){
        if([self.selectList containsObject:item]){
            [self.selectList removeObject:item];
        }else{
            [self.selectList addObject:item];
        }
    }
    else if(self.checkType == YHCheckBoxSelectMultipleAtLeastOne){
        if([self.selectList containsObject:item]){
            if(self.selectList.count == 1){
                YHHUDMsg(@"至少保留一个");
                return;
            }else{
                [self.selectList removeObject:item];
            }
        }else{
            [self.selectList addObject:item];
        }
    }
    if(self.clickBlock){
        self.clickBlock(self.selectList, self);
    }
    if(self.clickCurrentBlock){
        self.clickCurrentBlock(item,indexPath.row,self);
    }
    [collectionView reloadData];
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    YHCheckBoxItem * item = self.dataList[indexPath.row];
    if(self.config.scrollDirection == UICollectionViewScrollDirectionVertical){
        CGSize size = CGSizeMake(CGRectGetWidth(collectionView.frame), 0);
        CGFloat height = [item.title boundingRectWithSize:CGSizeMake(size.width-35, FLT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont yh_pfOfSize:14]} context:NULL].size.height;
        size.height = MAX(height, 44);
        return size;
    }else{
        CGSize size = CGSizeMake(0, CGRectGetHeight(collectionView.frame));
        CGFloat width = [item.title boundingRectWithSize:CGSizeMake(FLT_MAX, size.height) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont yh_pfOfSize:14]} context:NULL].size.width;
        size.width = width + 35;
        return size;
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return self.config.space;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return self.config.space;
}


@end



@implementation YHCheckBoxItem

@end

@implementation YHCheckBoxLayoutConfig

-(void)yh_commonInit{
    self.space = 25;
    
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
}

@end
